#include "Knight.h"
#include "DestroyGameObjectMessage.h"
#include "Game.h"
#include "AnimationSystem.h"
#include "GameplayState.h"
#include "Player.h"
//#include "CreateBulletMessage.h"
#include "Projectile.h"
#include "../SGD Wrappers/SGD_AudioManager.h"
#include "../SGD Wrappers/SGD_EventManager.h"

Knight::Knight()
{
	SetCurrAnimation("knightwalking");
	AnimationSystem::GetInstance()->StartPlaying(animInfo);
	AnimationSystem::GetInstance()->StartLooping(animInfo);
}

Knight::~Knight()
{
	if (GetAugment())
	{
		DestroyGameObjectMessage *msg = new DestroyGameObjectMessage{ GetAugment() };
		msg->SendMessageNow();
	}
}

void Knight::Update(float elapsedTime)
{
	Enemy::Update(elapsedTime);
	if (!updating) return;
}

/*virtual*/ bool Knight::DoAttack()
{
	return ((GameplayState::GetInstance()->GetPlayer()->GetPosition() - m_ptPosition).ComputeLength() < Game::GetInstance()->GetScreenWidth() / 3);
}

/*virtual*/ void Knight::Attack()
{
	GameplayState *gameplay = GameplayState::GetInstance();
	SGD::Point playerPos = gameplay->GetPlayer()->GetPosition();

	if (abs(playerPos.x - m_ptPosition.x) > 50.0f)
		MoveTowardsPlayer();
	else
	{
		//Attack (lowering sheild)
		if (animInfo.GetCurrAnimation() != "knightattacking")
			StartAnimation("knightattacking");

		m_vtVelocity.x = 0.0f;
	}
}

/*virtual*/ void Knight::EnterIdle()
{
	if (state == State::IDLE) return;
	Enemy::EnterIdle();

	StartAnimation("knightidle");
}

/*virtual*/ void Knight::EnterPatrol()
{
	if (state == State::PATROL) return;
	Enemy::EnterPatrol();

	StartAnimation("knightwalking");
}

/*virtual*/ void Knight::EnterCloseIn()
{
	if (state == State::CLOSEIN) return;
	Enemy::EnterCloseIn();

	StartAnimation("knightwalking");
}

void Knight::MoveTowardsPlayer()
{
	GameplayState *gameplay = GameplayState::GetInstance();
	SGD::Point playerPos = gameplay->GetPlayer()->GetPosition();

	if (animInfo.GetCurrAnimation() != "knightwalking")
	{
		StartAnimation("knightwalking");
	}

	//Move towards player
	if (playerPos.x < m_ptPosition.x)
		MoveLeft(150);
	else
		MoveRight(150);
}

/*virtual*/ void Knight::MoveLeft(float speed)
{
	Enemy::MoveLeft(speed);
}

/*virtual*/ void Knight::MoveRight(float speed)
{
	Enemy::MoveRight(speed);
}

void Knight::HandleCollision(GameObject* pOther)
{
	if (pOther->GetType() == MovingObject::OBJ_BULLET)
	{
		// don't shoot yourself
		if (((Projectile *)pOther)->GetOwner() == this) return;

		// call MovingObjects HandleCollision
		MovingObject::HandleCollision(pOther);

		// if knight dies notify archers
		if (m_iHealth <= 0)
			SGD::EventManager::GetInstance()->SendEventNow(new SGD::Event("KNIGHT_DIED", nullptr, this));
		
		// play hit sfx
		SGD::AudioManager::GetInstance()->PlayAudio(damageAudio);
	}

	CharacterCollision(pOther);
}
